﻿using Enum;
using MediatR;
using Practice.Common.Domains;
using Practice.Common.Dto;
using Practice.Common.Infrastructure.Interfaces;

namespace Practice.API.Application.Commands.UserW
{
    public class UserCreateHandler:IRequestHandler<UserCreateCommand ,Result>
    {
        public readonly IBaseRepository<Users> UsersRepository;
        public readonly IBaseRepository<UserRole> UserRoleRepository;

        public UserCreateHandler(IBaseRepository<Users> usersRepository, IBaseRepository<UserRole> userRoleRepository)
        {
            UsersRepository = usersRepository;
            UserRoleRepository = userRoleRepository;
        }

        public async Task<Result> Handle(UserCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.Added };
            try
            {
                var res = new Users()
                {
                    UserName = request.UserName,
                    Pwd = request.Pwd,
                };
                UsersRepository.Add(res);
                var res1 = new UserRole()
                {
                   UserId = res.UserId,
                   RoleId = request.RoleId,
                   UserRoleMassage = request.UserRoleMassage,
                    CreateTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
                };
                UserRoleRepository.Add(res1);
                if (res != null)
                {
                    result.Code = (int)CommonEnumCode.Success;
                }

            }
            catch (Exception)
            {

                result.Msg = "用户添加失败";
            }
            return result;
        }
    }
}
